package cn.tedu.es.criteria;

import cn.tedu.es.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.SearchOperations;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

@Component
public class StudentSearcher {
    /**
     * 用来执行搜索查询的一个工具对象
     * 可以执行三种查询：
     *      Criteria
     *      String
     *      Native
     */
    @Autowired
    private SearchOperations operations;// 在自动配置类里面创建好了

    public List<Student> findByBirthday(String birthday) {
        // 使用 Criteria 设置搜索条件：birthday="xxxx-xx-xx"
        Criteria criteria = new Criteria("birthday").is("1998-05-09");

        // 执行 criteria 查询
        return exec(criteria, null);
    }

    public List<Student> findByBirthday(String from, String to, Pageable pageable) {
        Criteria criteria = new Criteria("birthday").between(from, to);
        return exec(criteria, pageable);
    }

    private List<Student> exec(Criteria criteria, Pageable pageable) {
        CriteriaQuery query = new CriteriaQuery(criteria);
        query.setPageable(pageable);
        SearchHits<Student> hits = operations.search(query, Student.class);
        // 集合流式编程
        List<Student> list = hits.stream().map(SearchHit::getContent).collect(Collectors.toList());
        return list;
    }
}
